package com.top145;

import java.util.HashMap;
import java.util.LinkedList;

//https://leetcode.cn/problems/basic-calculator/solutions/646865/shuang-zhan-jie-jue-tong-yong-biao-da-sh-olym/
public class Solution224 {
    LinkedList<Integer> nums = new LinkedList<>();
    LinkedList<Character> op = new LinkedList<>();

    public int calculate(String s) {
        s = "0" + s;
        s = s.replaceAll(" ", "");
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                op.addLast(c);
            } else if (c == ')') {
                while (!op.isEmpty() && op.getLast() != '(') cacl();
                op.removeLast();
            } else if (c >= '0' && c <= '9') {
                int x = 0;
                while (i < s.length() && s.charAt(i) >= '0' && s.charAt(i) <= '9') x = 10 * x + s.charAt(i++) - '0';
                i--;
                nums.addLast(x);
            } else {
                //"1-(     -2)"
                if (i > 0 && s.charAt(i - 1) == '(') nums.addLast(0);
                while (!op.isEmpty() && op.getLast() != '(') cacl();
                op.addLast(c);
            }
        }
        while (!op.isEmpty()) cacl();
        return nums.getLast();
    }

    public void cacl() {
        int n2 = nums.removeLast();
        int n1 = nums.removeLast();
        char pop = op.removeLast();
        if (pop == '+') nums.addLast(n1 + n2);
        else nums.addLast(n1 - n2);
    }

}
